﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Security;
using YueRu.Common.Encrypt;

namespace YueRu.Common
{
    public sealed class ComHelper
    {
        /// <summary>
        /// 获取post/get集合
        /// </summary>
        /// <param name="ignoreCase">true 不区分大小写，统一返回小写  false 区分大小写</param>
        /// <returns></returns>
        public static SortedDictionary<string, string> GetRequestSortDic(bool ignoreCase)
        {
            int i = 0;
            var sArray = new SortedDictionary<string, string>();
            NameValueCollection coll = HttpContext.Current.Request.Form;
            String[] requestItem = coll.AllKeys;
            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(ignoreCase ? requestItem[i].ToLower() : requestItem[i], GetString(requestItem[i]));
            }

            coll = HttpContext.Current.Request.QueryString;
            requestItem = coll.AllKeys;
            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(ignoreCase ? requestItem[i].ToLower() : requestItem[i], GetString(requestItem[i]));
            }

            return sArray;
        }

        public static async Task<SortedDictionary<string, string>> GetRequestSortDic(
            HttpControllerContext controllerContext)
        {
            var sArray = new SortedDictionary<string, string>();
            var stream = await controllerContext.Request.Content.ReadAsStreamAsync();
            if (stream.Position > 0) //如果使用了Model映射参数数据流的游标位置改变了
                stream.Position = 0;
            var s = stream;
            var b = new byte[s.Length];
            s.Read(b, 0, (int)s.Length);
            var postStr = Encoding.UTF8.GetString(b);
            if (!string.IsNullOrEmpty(postStr))
            {

                var arr = postStr.Split('&');
                if (arr.Any())
                {
                    foreach (var item in arr)
                    {
                        var itemArr = item.Split('=');
                        if (itemArr.Any() && itemArr.Count() == 2)
                        {
                            sArray.Add(itemArr[0].ToLower(), HttpUtility.UrlDecode(itemArr[1]));
                        }
                    }
                }
            }
            stream.Position = 0;
            return sArray;
        }

        /// <summary>
        /// 从当前环境中获取
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        private static string GetString(string name)
        {
            string res = "";
            var v = HttpContext.Current.Request[name];
            if (v != null)
            {
                res = Convert.ToString(v);
                //res = v.ToString();
            }
            return res;
        }

        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime ConvertIntDateTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            var toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">原串</param>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        private static string ToMd5(string str, string privateKey)
        {
            var str2 = (str + privateKey).ToLower();
            return YueRuMd5.Md5(str2);
        }

        /// <summary>
        /// 获取Sign
        /// </summary>
        /// <param name="inputPara"></param>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static string GetResponseMysign(SortedDictionary<string, string> inputPara, string privateKey)
        {
            string fullstring = GetPostStrings(inputPara, "sign");
            return ToMd5(fullstring, privateKey);
        }
        private static string GetPostStrings(SortedDictionary<string, string> inputPara, string excepted)
        {
            //var sPara = new Dictionary<string, string>();

            //过滤空值、sign与sign_type参数
            //foreach (KeyValuePair<string, string> temp in inputPara)
            //{
            //    if (temp.Key.ToLower() != excepted && !string.IsNullOrEmpty(temp.Value))
            //    {
            //        sPara.Add(temp.Key.ToLower(), temp.Value);
            //    }
            //}

            //获得签名结果
            var prestr = new StringBuilder();
            foreach (KeyValuePair<string, string> temp in inputPara)
            {
                if (temp.Key.ToLower() != excepted)
                    prestr.Append(temp.Key + "=" + temp.Value + "&");
            }

            //去掉最後一個&字符
            int nLen = prestr.Length;
            if (nLen > 1)
                prestr.Remove(nLen - 1, 1);
            return prestr.ToString();
        }

        /// <summary>
        /// 获取十位的时间戳
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string GenerateTimeStamp(DateTime dt)
        {
            // Default implementation of UNIX time of the current UTC time  
            TimeSpan ts = dt.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

    }
}
